<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">

      <el-input @keyup.enter.native="handleFilter" v-model="listQuery.regionName" style="width: 200px;" class="filter-item" placeholder="区域名称" clearable>
      </el-input>

      <el-select clearable style="width:120px" class="filter-item" v-model="listQuery.regionLevel" placeholder="区域等级">
        <el-option v-for="item in regionLevel" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button v-if="sys_region_add1" class="filter-item" style="margin-left: 10px;" @click="handleCreate1" type="primary" icon="edit">添加航站楼</el-button>
      <el-button v-if="sys_region_add2" class="filter-item" style="margin-left: 10px;" @click="handleCreate2" type="primary" icon="edit">添加一级区域</el-button>
      <el-button v-if="sys_region_add3" class="filter-item" style="margin-left: 10px;" @click="handleCreate3" type="primary" icon="edit">添加二级区域</el-button>

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleDownload">导出</el-button>

    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" stripe border fit highlight-current-row style="width: 100%">

      <!-- <el-table-column align="center" label="ID">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="区域编码">
        <template slot-scope="scope">
          <span>
           {{scope.row.regionCode}}
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="区域名">
        <template slot-scope="scope">
          <span>{{scope.row.regionName}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="父级编码">
        <template slot-scope="scope">
          <span>{{scope.row.regionCodeP}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="父级区域名">
        <template slot-scope="scope">
          <span>{{scope.row.regionNameP}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="顶级编码">
        <template slot-scope="scope">
          <span>{{scope.row.regionCodeD}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="顶级区域名">
        <template slot-scope="scope">
          <span>{{scope.row.regionNameD}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="status-col" label="等级">
        <template slot-scope="scope">
          <el-tag>{{scope.row.regionLevel | statusFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="sys_region_upd" size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="sys_region_del" size="small" type="danger" @click="deletes(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        
        <el-form-item label="名称" prop="regionName">
          <el-input v-model="form.regionName" placeholder="请输入名称"></el-input>
        </el-form-item>

        <!-- <el-form-item v-if="dialogStatus=='update'" label="区域级别" prop="regionLevel">
          <el-select class="filter-item" v-model="form.regionLevel" @change="changeLevel" placeholder="请选择">
            <el-option v-for="item in regionLevelOptions" :key="item" :label="item | statusFilter" :value="item"> </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item v-if="dialogStatus=='create2' || dialogStatus=='create3' || regionLevelStatus=='2' || regionLevelStatus=='3'" label="航站楼" prop="parentIdD">
          <el-select class="filter-item" v-model="form.parentIdD" placeholder="请选择" @change="selectHang">
            <el-option v-for="item in allHang" :key="item.id" :label="item.regionName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="dialogStatus=='create3' || (dialogStatus=='update' && regionLevelStatus=='3')" label="上级区域" prop="regionParentId">
          <el-select class="filter-item" v-model="form.regionParentId" placeholder="请选择">
            <el-option v-for="item in allRegion" :key="item.id" :label="item.regionName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus!='update'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, getRegionByPid } from '@/api/region/region'
import waves from '@/directive/waves/index.js' // 水波纹指令
// import { parseTime } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  name: 'table_region',
  directives: {
    waves
  },
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        regionName: '',
        regionLevel: ''
      },
      form: {
        regionCode: '',
        regionName: '',
        regionParentId: '',
        regionLevel: '',
        regionCodeP: '',
        regionNameP: '',
        parentIdD: '',
        regionCodeD: '',
        regionNameD: ''
      },
      regionLevel: [
        {
          label: '航站楼',
          value: 1
        },
        {
          label: '一级区域',
          value: 2
        },
        {
          label: '二级区域',
          value: 3
        }
      ],
      rules: {
        regionName: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        regionLevel: [
          {
            required: true,
            message: '请选择级别',
            trigger: 'blur'
          }
        ],
        parentIdD: [
          {
            required: true,
            message: '请选择航站楼',
            trigger: 'blur'
          }
        ],
        regionParentId: [
          {
            required: true,
            message: '请选择上级',
            trigger: 'blur'
          }
        ]
      },
      regionLevelOptions: [1, 2, 3],
      dialogFormVisible: false,
      dialogStatus: '',
      regionLevelStatus: '',
      allHang: [],
      allRegion: [],
      textMap: {
        update: '编辑',
        create1: '新建航站楼',
        create2: '新建一级区域',
        create3: '新建二级区域'
      },
      tableKey: 0
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '航站楼',
        2: '一级区域',
        3: '二级区域'
      }
      return statusMap[status]
    }
  },
  created() {
    this.getList()
    this.sys_region_add1 = this.permissions['sys_region_add1']
    this.sys_region_add2 = this.permissions['sys_region_add2']
    this.sys_region_add3 = this.permissions['sys_region_add3']
    this.sys_region_upd = this.permissions['sys_region_upd']
    this.sys_region_del = this.permissions['sys_region_del']
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.orderByField = '`r1`.region_level'
      this.listQuery.isAsc = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleCreate1() {
      this.resetTemp()
      this.regionLevelStatus = 1
      this.form.regionLevel = 1
      this.form.regionParentId = 0
      this.dialogStatus = 'create1'
      this.dialogFormVisible = true
    },
    handleCreate2() {
      this.resetTemp()
      this.dialogStatus = 'create2'
      this.form.regionLevel = 2
      this.dialogFormVisible = true
      getRegionByPid(0).then(response => {
        this.allHang = response.data
      })
    },
    handleCreate3() {
      this.resetTemp()
      this.dialogStatus = 'create3'
      this.form.regionLevel = 3
      this.dialogFormVisible = true
      getRegionByPid(0).then(response => {
        this.allHang = response.data
      })
    },
    handleUpdate(row) {
      getObj(row.id).then(response => {
        this.form = response.data
        // this.form.regionParentId = response.data.regionNameP
        if (response.data.regionLevel === 2) {
          this.form.parentIdD = response.data.regionParentId
        }
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.regionLevelStatus = this.form.regionLevel
        getRegionByPid(0).then(response => {
          this.allHang = response.data
        })
        getRegionByPid(this.form.parentIdD).then(response => {
          this.allRegion = response.data
        })
      })
    },
    selectHang(pid) {
      getRegionByPid(pid).then(response => {
        this.allRegion = response.data
      })
    },
    changeLevel() {
      this.regionLevelStatus = this.form.regionLevel
    },
    create(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    deletes(row) {
      this.$confirm(
        '此操作将永久删除该区域及其下级区域, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.id)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    resetTemp() {
      this.form = {
        id: undefined,
        regionCode: '',
        regionName: '',
        regionParentId: '',
        regionLevel: '',
        regionCodeP: '',
        regionNameP: '',
        parentIdD: '',
        regionCodeD: '',
        regionNameD: ''
      }
    },
    handleDownload() {
      const lq = this.listQuery
      lq.limit = this.total
      fetchList(lq).then(response => {
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = ['区域编码', '区域名', '父级编码', '父级区域名', '顶级编码', '顶级区域名', '等级']
          const filterVal = ['regionCode', 'regionName', 'regionCodeP', 'regionNameP', 'regionCodeD', 'regionNameD', 'regionLevel']
          const list = response.data.records
          for (const item of list) {
            switch (item.regionLevel) {
              case 1:
                item.regionLevel = '航站楼'
                break
              case 2:
                item.regionLevel = '一级区域'
                break
              case 3:
                item.regionLevel = '二级区域'
                break
            }
          }
          this.listLoading = false
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '区域信息')
        })
        this.listQuery.limit = 20
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>
